<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>给数字加上千分位</title>
</head>
<body>
    <script>
        // 倒序遍历
        function qianfenwei(num) {
        num += '';
        let result = '';
        num = num.split('').reverse();
        num.forEach((v, i) => {
            result = v + result;
            if (i % 3 === 2 && i !== num.length - 1) {
            result = ',' + result;
            }
        });
        console.log(result);
        return result;
        }
        // 分开处理
        function qianfenwei2(num) {
        const len = num.length;
        const remainderLen = len % 3;
        const result = remainderLen ? [num.substring(0, remainderLen)] : [];
        for (let i = remainderLen; i < len; i += 3) {
            result.push(num.substring(i, i + 3));
        }
        console.log(result.join(','));
        return result.join(',');
        }
        // 正则表达式
        function qianfenwei3(num) {
        const result = num.replace(/(?<!^)(?=(\d{3})+$)/g, ',');
        console.log(result);
        return result;
        }
    </script>
</body>
</html>